package com.gill.demo;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @Title: ZKConnectDemo.java
 * @Description: zookeeper 恢复之前的会话连接demo演示
 */
public class ZKConnectSessionWatcher implements Watcher {
	
	final static Logger log = LoggerFactory.getLogger(com.gill.demo.ZKConnect.class);

	public static final String zkServerPath = "env:2181";
	public static final Integer timeout = 5000;
	
	public static void main(String[] args) throws Exception {
		
		ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher());
		
		log.warn("客户端开始连接zookeeper服务器...");
		log.warn("连接状态：{}", zk.getState());
		new Thread().sleep(1000);//连接需要时间
		log.warn("连接状态：{}", zk.getState());

		// 由于zookeeper的客户端连接是异步的，所以不能在new zookeeper()后直接获取sessionId,否则会得到0，需要建立连接之后再获取sessionId
		long sessionId = zk.getSessionId();
		byte[] sessionPassword = zk.getSessionPasswd();
		
		// 开始会话重连，可以到zk服务端，使用echo dump | nc localhost 2181
		log.warn("开始会话重连...");
		
		ZooKeeper zkSession = new ZooKeeper(zkServerPath,
											timeout, 
											new ZKConnectSessionWatcher(),
											sessionId, 
											sessionPassword);
		log.warn("重新连接状态zkSession：{}", zkSession.getState());
		new Thread().sleep(1000);
		log.warn("重新连接状态zkSession：{}", zkSession.getState());
		// debug:查看重连之后的sessionId是否和之前保持一致
		long newSessionId = zkSession.getSessionId();
	}
	
	@Override
	public void process(WatchedEvent event) {
		log.warn("接受到watch通知：{}", event);
	}
}

